package top.overstep.zboot.system.commons.shiro;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
public class RedisCacheManager implements CacheManager {
    /**
     * 对redis 操作模板了类
     */
    @Setter
    private RedisTemplate redisTemplate;
    /**
     * 保存redisCache
     */
    private static final ConcurrentMap<String,Cache> CACHES = new ConcurrentHashMap<>();
    /**
     * redis key 前缀
     */
    public static final String DEFAULT_CACHE_KEY_PREFIX = "shiro:cache:";
    /**
     * redis key 过期时间 单位：秒
     */
    @Value("${shiro.cache.expire}")
    private Long expire;

    /**
     * 获取缓存实现
     * @param name 缓存名称
     * @param <K> key泛型
     * @param <V> value泛型
     * @return
     * @throws CacheException
     */
    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        log.debug("get cache ,name  = {}",name);
        Cache<K,V> cache = CACHES.get(name);
        if(cache==null){
            cache = new RedisCache<>(redisTemplate,expire,DEFAULT_CACHE_KEY_PREFIX+name+":");
            CACHES.put(name,cache);
        }
        return cache;
    }
}
